package net.wanho.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import net.wanho.dto.LoginUserDTO;
import net.wanho.mapper.UserInfoMapper;
import net.wanho.po.UserInfo;
import net.wanho.service.LoginService;
import net.wanho.util.CurrentUtil;
import net.wanho.util.JwtUtil;
import net.wanho.vo.LoginUserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * Author：汤小洋
 * Date：2025-01-12 17:03
 * Description：<描述>
 */
@Service
@RequiredArgsConstructor
public class LoginServiceImpl implements LoginService {

    private final UserInfoMapper userInfoMapper;

    @Override
    public String login(LoginUserDTO loginUserDTO) {
        /**
         * 判断验证码
         */


        /**
         * 判断用户
         */
        LambdaQueryWrapper<UserInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserInfo::getUserCode, loginUserDTO.getUserCode());
        wrapper.eq(UserInfo::getUserPwd, SecureUtil.md5(loginUserDTO.getUserPwd()));
        UserInfo userInfo = userInfoMapper.selectOne(wrapper);
        if (ObjectUtils.isEmpty(userInfo)){
            throw new RuntimeException("用户名或密码不正确！");
        }
        if (userInfo.getUserState().equals("0")){
            throw new RuntimeException("用户已被禁用！");
        }

        /**
         * 生成token
         */
        Map<String, Object> payload = new HashMap<>();
        payload.put("userId", userInfo.getUserId());
        payload.put("userCode", userInfo.getUserCode());
        payload.put("userName", userInfo.getUserName());
        payload.put("userType", userInfo.getUserType());
        String token = JwtUtil.generate(payload);

        return "Bearer " + token;
    }

    @Override
    public LoginUserVo getCurrentUser() {
        Integer userId = CurrentUtil.getId();
        UserInfo userInfo = userInfoMapper.selectById(userId);

        LoginUserVo loginUserVo = new LoginUserVo();
        BeanUtils.copyProperties(userInfo, loginUserVo);
        return loginUserVo;
    }
}
